package com.example.zx.theline;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Network;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import GsonBean.IsLogin;
import GsonBean.NewAppBean;
import Utils.DictionariesUtil;
import app.MyApplication;
import base.BaseActivity;
import dialog.NewAppDialog;
import greendao.UserDao;
import network.BaseCallBack;
import network.NetWorkApi;
import network.ObjectHttpResponseHandler;
import Utils.MyToast;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import user.LoginUser;

@SuppressWarnings("unused")
public class MainActivity extends BaseActivity {
    EditText mUsername, mPassword;
    String username, password;
    Button mButton;
    NewAppDialog mNewAppDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        MyApplication.APP_STATUS = 1;
        InitView();
        InitData();
        InitListen();
        //检查APP是否需要更新
        getApp();
    }

    @Override
    protected void InitView() {
        mUsername = (EditText) findViewById(R.id.username);
        mPassword = (EditText) findViewById(R.id.password);
        mButton = (Button) findViewById(R.id.login);
    }

    @Override
    protected void InitData() {
        getUserNameInSp();
    }


    private boolean checkApp(NewAppBean mBean) {
        PackageInfo packageInfo = null;
        if (packageInfo == null) {
            try {
                packageInfo = MyApplication.getInstance().getPackageManager().getPackageInfo(MyApplication.getInstance().getPackageName(),
                        0);
            } catch (PackageManager.NameNotFoundException e) {
            }
        }
        if (mBean.getInfo() != null && packageInfo.versionCode < mBean.getInfo().getVersionCode()) {
            return true;
        }
        return false;
    }

    //下载APP文件
    public void downLoadApp() {
        NetWorkApi.downLoadApp(MainActivity.this, new BinaryHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
                mNewAppDialog.dismiss();
                MyApplication.ShowWaitDialog(MainActivity.this);
                MyApplication.setWaitDialogMsg("请稍等，正在下载新版APP");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] binaryData) {
                try {
                    MyApplication.HideWaitDialog();
                    SaveAndInstallApp(binaryData);
                } catch (Exception e) {
                    MyToast.showFail();

                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] binaryData, Throwable error) {
                MyApplication.setWaitDialogMsg("下载失败请检查网络");
            }
        });
    }


    //将APP文件存到本地
    private void SaveAndInstallApp(byte[] binaryData) {

        /**
         * 创建File对象，其中包含文件所在的目录以及文件的命名
         */
        File file = new File(Environment.getExternalStorageDirectory(),
                "app-ljyyx.apk");
        // 创建FileOutputStream对象
        FileOutputStream outputStream = null;
        // 创建BufferedOutputStream对象
        BufferedOutputStream bufferedOutputStream = null;
        try {
            // 如果文件存在则删除
            if (file.exists()) {
                deleteFileSafely(file);
            }
            // 在文件系统中根据路径创建一个新的空文件
            file.createNewFile();
            // 获取FileOutputStream对象
            outputStream = new FileOutputStream(file);
            // 获取BufferedOutputStream对象
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            // 往文件所在的缓冲输出流中写byte数据
            bufferedOutputStream.write(binaryData);
            // 刷出缓冲输出流，该步很关键，要是不执行flush()方法，那么文件的内容是空的。
            bufferedOutputStream.flush();
            outputStream.flush();
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
        } finally {
            // 关闭创建的流对象
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }


    /**
     * 在安卓设备上更安全的删除文件
     * 问题：安卓设备上，删除文件后如果立即创建同名的文件，将会报 EBUSY (Device or resource busy)错误
     * 解决：给文件重命名，然后再删除
     *
     * @param target
     */
    public static void deleteFileSafely(File target) {
        if (target == null || !target.exists()) {
            return;
        }

        File temp = new File(target.getAbsolutePath() + "xgjlasjgoasjg");
        target.renameTo(temp);
        temp.delete();
    }


    @Override
    protected void InitListen() {
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                username = mUsername.getText().toString();
                password = mPassword.getText().toString();
                if (username.equals("") || password.equals("")) {
                    MyToast.showToast("请填写用户名跟密码！");
                    return;
                }
                MyApplication.ShowWaitDialog(MainActivity.this);
                MyApplication.setWaitDialogMsg("登陆中....");
                Map<String, String> map = new HashMap();
                map.put("userName", username);
                map.put("userPsw", password);
                NetWorkApi.login(map, new BaseCallBack<IsLogin>() {

                    @Override
                    public void Success(Call<IsLogin> call, Response<IsLogin> response) {
                        try {
                            IsLogin mIsLogin = response.body();

                            if (mIsLogin.getMsg().equals("failed")) {
                                MyApplication.HideWaitDialog();
                                Toast.makeText(MainActivity.this, "用户名密码错误", Toast.LENGTH_SHORT).show();
                            }
                            if (mIsLogin.getMsg().equals("success")) {
                                getLoginUser(mIsLogin);
                                saveUsername();
                                MyApplication.HideWaitDialog();
                                Intent intent = new Intent(MainActivity.this, BodyActivity.class);
                                startActivity(intent);
                            }
                        } catch (Exception e) {
                            MyToast.showFail();
                        }
                    }

                    @Override
                    public void Failure(Call<IsLogin> call, Throwable t) {
                        MyToast.showFail();
                    }

                    @Override
                    public void onFinally() {
                    }

                });
            }
        });
    }
//                NetWorkApi.login(MainActivity.this, map, new ObjectHttpResponseHandler(MainActivity.this, IsLogin.class) {
//                    @Override
//                    public void Success(int i, Header[] headers, Object object) {
//                        try {
//                            IsLogin mIsLogin = (IsLogin) object;
//                            if (mIsLogin.getMsg() == null) {
//                                MyToast.showServerError(MainActivity.this);
//                                return;
//                            }
//                            if (mIsLogin.getMsg().equals("failed")) {
//                                MyToast.showToast("用户名密码错误");
//                            }
//                            if (mIsLogin.getMsg().equals("success")) {
//                                getLoginUser(mIsLogin);
//                                saveUsername();
//                                MyApplication.HideWaitDialog();
//                                Intent intent = new Intent(MainActivity.this, BodyActivity.class);
//                                startActivity(intent);
//                            }
//                        } catch (Exception e){
//                            MyToast.showServerError(MainActivity.this);
//                        }
//
//                    }
//
//                    @Override
//                    public void Failure(int i, Header[] headers, String s, Throwable throwable) {
//                        super.Failure(i, headers, s, throwable);
//                        MyToast.showFail();
//                    }
//
//                    @Override
//                    public void onFinish() {
//                        super.onFinish();
//                    }
//                });
//            }
//        });


    private void getApp() {
        MyApplication.ShowWaitDialog(this);
        MyApplication.setWaitDialogMsg("正在校对APP版本");
        NetWorkApi.getApp(new Callback<NewAppBean>() {
                              @Override
                              public void onResponse(Call<NewAppBean> call, Response<NewAppBean> response) {
                                  try {
                                      NewAppBean mBean = response.body();
//                                      if (true) {
                                      if (checkApp(mBean)) {
                                          mNewAppDialog = new NewAppDialog(MainActivity.this);
                                          mNewAppDialog.setonClick(new NewAppDialog.onClick() {
                                              @Override
                                              public void confirm() {
                                                  //下载APP
                                                  downLoadApp();
                                              }

                                              //取消更新
                                              @Override
                                              public void cancel() {
                                                  //什么都不做
                                              }
                                          });
                                          mNewAppDialog.show();
                                      } else {
                                          MyApplication.HideWaitDialog();
                                      }
                                  } catch (Exception e) {
                                      MyApplication.setWaitDialogMsg("APP版本检测错误请联系技术人员,请谨慎使用！！");
                                  }
                              }

                              @Override
                              public void onFailure(Call<NewAppBean> call, Throwable t) {
                                  MyToast.showFail();
                                  MyApplication.setWaitDialogMsg("APP版本检测错误请联系技术人员,请谨慎使用！！");
                              }
                          }
        );
    }

    public void getLoginUser(IsLogin mIsLogin) {
        LoginUser mLoginUser = new LoginUser();
        mLoginUser.setUserDisplayName(mIsLogin.getInfo().getUserName());
        mLoginUser.setUserMobilephone(mIsLogin.getInfo().getUserMobilephone());
        mLoginUser.setUserUnitId(mIsLogin.getInfo().getUserUnitId());
        mLoginUser.setUserUnitName(mIsLogin.getInfo().getUserUnitName());
        mLoginUser.setTrueName(mIsLogin.getInfo().getUserDisplayName());
        mLoginUser.setUserAuthority(mIsLogin.getInfo().getUserAuthority());
        if (mLoginUser.getUserUnitType() == null) {
            mLoginUser.setUserUnitType("");
        } else {
            mLoginUser.setUserUnitType(mLoginUser.getUserUnitType());
        }

        for (IsLogin.InfoBean.UserMenuAuthorityBean MenuBean : mIsLogin.getInfo().getUserMenuAuthority()) {
            switch (MenuBean.getMenuCode()) {
                case "12020000":
                    for (int i = 0; i < MenuBean.getChildren().size(); i++) {
                        if (MenuBean.getChildren().get(i).getMenuCode().equals("12020300")) {
                            mLoginUser.getSgyjh().setShyjh(true);
                        }
                        if (MenuBean.getChildren().get(i).getMenuCode().equals("12020400")) {
                            mLoginUser.getSgyjh().setShywc(true);
                        }
                        if (MenuBean.getChildren().get(i).getMenuCode().equals("12020500")) {
                            mLoginUser.getSgyjh().setSpywc(true);
                        }
                        if (MenuBean.getChildren().get(i).getMenuCode().equals("12020600")) {
                            mLoginUser.getSgyjh().setYjhcx(true);
                        }
                    }
                    //如果所有子菜单都为false 则父菜单 false
                    if (mLoginUser.getSgyjh().isShyjh()
                            || mLoginUser.getSgyjh().isShywc()
                            || mLoginUser.getSgyjh().isSpywc()
                            || mLoginUser.getSgyjh().isYjhcx()) {
                        mLoginUser.getSgyjh().setSgyjh(true);
                    }
                    break;
                case "12030000":
                    for (int i = 0; i < MenuBean.getChildren().size(); i++) {
                        if (MenuBean.getChildren().get(i).getMenuCode().equals("12030200")) {
                            mLoginUser.getSgzjh().setShzjh(true);
                        }
                        if (MenuBean.getChildren().get(i).getMenuCode().equals("12030300")) {
                            mLoginUser.getSgzjh().setShywc(true);
                        }
                        if (MenuBean.getChildren().get(i).getMenuCode().equals("12030400")) {
                            mLoginUser.getSgzjh().setZjhcx(true);
                        }
                    }
                    //如果所有子菜单都为false 则父菜单 false
                    if (mLoginUser.getSgzjh().isShzjh()
                            || mLoginUser.getSgzjh().isShywc()
                            || mLoginUser.getSgzjh().isZjhcx()) {
                        mLoginUser.getSgzjh().setSgzjh(true);
                    }
                    break;
                case "12040000":
                    for (int i = 0; i < MenuBean.getChildren().size(); i++) {
                        if (MenuBean.getChildren().get(i).getMenuCode().equals("12040200")) {
                            mLoginUser.getSgrjh().setShrjh(true);
                        }
                        if (MenuBean.getChildren().get(i).getMenuCode().equals("12040300")) {
                            mLoginUser.getSgrjh().setShywc(true);
                        }
                        if (MenuBean.getChildren().get(i).getMenuCode().equals("12040400")) {
                            mLoginUser.getSgrjh().setRjhcx(true);
                        }
                    }
                    //如果所有子菜单都为false 则父菜单 false
                    if (mLoginUser.getSgrjh().isShrjh()
                            || mLoginUser.getSgrjh().isShywc()
                            || mLoginUser.getSgrjh().isRjhcx()) {
                        mLoginUser.getSgrjh().setSgrjh(true);
                    }
                    break;
                case "12050000":
                    for (int i = 0; i < MenuBean.getChildren().size(); i++) {
                        if (MenuBean.getChildren().get(i).getMenuCode().equals("12050100")) {
                            mLoginUser.getJdjc().setSgjhryap(true);
                        }
                        if (MenuBean.getChildren().get(i).getMenuCode().equals("12050200")) {
                            mLoginUser.getJdjc().setSgjhrycx(true);
                        }
                        if (MenuBean.getChildren().get(i).getMenuCode().equals("12050201")) {
                            mLoginUser.getJdjc().setJdjclrxx(true);
                        }
                        if (MenuBean.getChildren().get(i).getMenuCode().equals("12050300")) {
                            mLoginUser.getJdjc().setJdjcdcl(true);
                        }
                        if (MenuBean.getChildren().get(i).getMenuCode().equals("12050400")) {
                            mLoginUser.getJdjc().setJdjcycl(true);
                        }
                        if (MenuBean.getChildren().get(i).getMenuCode().equals("12050500")) {
                            mLoginUser.getJdjc().setJdjcxxcx(true);
                        }
                    }
                    //如果所有子菜单都为false 则父菜单 false
                    //施工监护 权限
                    if (mLoginUser.getJdjc().isSgjhryap()
                            || mLoginUser.getJdjc().isSgjhrycx()) {
                        mLoginUser.getJdjc().setSgjh(true);
                    }
                    //检查录入 权限
                    if (mLoginUser.getJdjc().isJdjclrxx()
                            || mLoginUser.getJdjc().isJdjcdcl()
                            || mLoginUser.getJdjc().isJdjcycl()
//                            || mLoginUser.getJdjc().isJdjcxxcx()
                            ) {
                        mLoginUser.getJdjc().setJclr(true);
                    }
                    break;
                case "12060000":
                    for (int i = 0; i < MenuBean.getChildren().size(); i++) {
                        if (MenuBean.getChildren().get(i).getMenuCode().equals("12060100")) {
                            mLoginUser.getZsjh().setZsyjh(true);
                        }
                        if (MenuBean.getChildren().get(i).getMenuCode().equals("12060200")) {
                            mLoginUser.getZsjh().setZszbyjh(true);
                        }
                        if (MenuBean.getChildren().get(i).getMenuCode().equals("12060300")) {
                            mLoginUser.getZsjh().setZszjh(true);
                        }
                        if (MenuBean.getChildren().get(i).getMenuCode().equals("12060400")) {
                            mLoginUser.getZsjh().setZsrjh(true);
                        }
                    }
                    //如果所有子菜单都为false 则父菜单 false
                    if (mLoginUser.getZsjh().isZsyjh()
                            || mLoginUser.getZsjh().isZszbyjh()
                            || mLoginUser.getZsjh().isZszjh()
                            || mLoginUser.getZsjh().isZsrjh()) {
                        mLoginUser.getZsjh().setZsjh(true);
                    }
                    break;
            }
        }
        MyApplication.setmLoginUser(mLoginUser);
    }

    public void saveUsername() {
        SharedPreferences sp = getSharedPreferences("username", Activity.MODE_PRIVATE);
        SharedPreferences.Editor ed = sp.edit();
        ed.putString("username", username);
        ed.apply();
    }

    public void getUserNameInSp() {
        SharedPreferences sp = getSharedPreferences("username", Activity.MODE_PRIVATE);
        String username = sp.getString("username", null);
        if (username != null) {
            mUsername.setText(username);
        }
        String password = sp.getString("psw", null);
    }

}
